<?php

namespace App\Http\Controllers\Api\V1;

use App\B2BProject\Custom\Business\Invoice;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class InvoiceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $invoices = \Auth::user()->invoice()->get();

        $data = [];

        foreach ($invoices as $invoice) {
            $data[] = [
                'id'      => $invoice->id,
                'subject' => $invoice->subject,
            ];
        }

        return success_return(['list' => $data]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $validator = \Validator::make($request->all(), [
            'subject' => 'required'
        ]);

        if ($validator->fails()) {
            return error_return(900004, 403);
        }

        $invoice = Invoice::create();
        $invoice->subject = $request->subject;

        $invoice->save();

        \Auth::user()->invoice()->save($invoice);

        return success_return(['id' => $invoice->id]);
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  int                      $id
     *
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $validator = \Validator::make($request->all(), [
            'subject' => 'required'
        ]);

        if ($validator->fails()) {
            return error_return(900004, 403);
        }

        $invoice = \Auth::user()->invoice()->whereId($id)->firstOrFail();
        $invoice->subject = $request->subject;

        $invoice->save();

        return success_return(null);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        \Auth::user()->invoice()->whereId($id)->delete();

        return success_return(null);
    }
}
